package cn.usaiot.chat.video.videochat.call;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;


import cn.usaiot.chat.video.videochat.R;
import org.webrtc.EglBase;
import org.webrtc.PeerConnection;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
//https://github.com/JumpingYang001/webrtc
//https://blog.csdn.net/yyz_1987/article/details/102466439

public class VideoCallActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 5152;
    private static final String TAG = "VideoCallActivity";

    //private PeerConnection localPeer;
    private EglBase rootEglBase;
    private List<PeerConnection.IceServer> peerIceServers = new ArrayList<>();
    private boolean isSpeakerOn;
    private FloatingActionButton mSpeakerButton;

    //WebrtcPeer peer1;
    public static Context applicationContext;

    public static VideoCallActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_call);

        applicationContext = getApplicationContext();

        mSpeakerButton = (FloatingActionButton) findViewById(R.id.speaker_change);

        AudioManager audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
        isSpeakerOn = audioManager.isSpeakerphoneOn();

        if (isSpeakerOn) {
            mSpeakerButton.setImageResource(R.drawable.ic_speaker_phone);
        } else {
            mSpeakerButton.setImageResource(R.drawable.ic_speaker);
        }
        mSpeakerButton.setOnClickListener(this);

        activity = this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rootEglBase.releaseSurface();
    }


    public static boolean isStart = false;

    @Override
    protected void onStart() {
        super.onStart();

        if (isStart) return;
        //peer1 = new WebrtcPeer();
        //Intent intent = new Intent(VideoCallActivity.this, FloatingWindowService.class);

        //FloatingWindowService floatingWindowService = (FloatingWindowService)intent;

        //startService(intent);
        new Thread(()->{
            try {
                Thread.sleep(2000); //3000
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(()->{
                requestCameraPermission();
            });
        }).start();
        isStart = true;
    }



    @Override
    protected void onStop() {
        super.onStop();
    }



    /**
     * Closing up - normal hangup and app destroy
     */

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.end_call_button:
                hangup();
                break;
            case R.id.speaker_change:
                break;

        }
    }

    private void hangup() {
        try {
            android.os.Process.killProcess(android.os.Process.myPid());
            finish();
        } catch (Exception e) {
            android.os.Process.killProcess(android.os.Process.myPid());
            finish();
            e.printStackTrace();
        }

    }


    private void requestCameraPermission() {
        int hasCameraPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int hasAudioPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        int hasAlertPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW);
        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED || hasAudioPermission != PackageManager.PERMISSION_GRANTED
        || hasAlertPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,Manifest.permission.SYSTEM_ALERT_WINDOW}, CAMERA_PERMISSION_REQUEST_CODE);
        } else {
            //initStuff();
            //peer1.startPeer(rootEglBase, null, getApplicationContext());


            Intent intent = new Intent(VideoCallActivity.this, FloatingWindowService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//判断系统版本
                startForegroundService(intent);
            }
            else {
                startService(intent);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //initStuff();
                //peer1.startPeer(rootEglBase, null, getApplicationContext());

                Intent intent = new Intent(VideoCallActivity.this, FloatingWindowService.class);
                startService(intent);
            } else {
                Toast.makeText(this, R.string.camera_permission_fail, Toast.LENGTH_SHORT).show();
                android.os.Process.killProcess(android.os.Process.myPid());
                finish();
            }
        }
    }
}
